function ensureKey(root, path, keyOnly = false) {
    let target = root;
    const ids = path.split('.');
    const name = keyOnly ? undefined : ids.pop();
    for (const id of ids) {
        if (typeof target[id] !== 'object') {
            target[id] = {};
        }
        target = target[id];
    }
    return keyOnly ? target : [target, name];
}

/** 动态加载所有模块（actions和reducers） */
const modules = require.context('./data');

export const actions = {};
export const reducers = {};

modules.keys().forEach(key => {
    if (!/\.js$/.test(key)) {
        const ctx = modules(key);
        const id = key.substr(2).replace(/\//g, '.');
        if (ctx.actions && typeof ctx.default === 'function') {
            {
                const [target, name] = ensureKey(actions, id);
                target[name] = ctx.actions;
            }
            {
                const [target, name] = ensureKey(reducers, id);
                target[name] = ctx.default;
            }
        }
    }
});

import {combineReducers} from 'redux';

// 递归合并各级reducers
function combine(reducers) {
    if (typeof reducers === 'function') {
        return reducers;
    }
    const reducer = {};
    for (const name in reducers) {
        reducer[name] = combine(reducers[name]);
    }
    return combineReducers(reducer);
}

// 最顶层reducers不需要合并，因为外面还有一层合并
for (const name in reducers) {
    reducers[name] = combine(reducers[name]);
}
